package io.renren.handler;


import cn.hutool.core.collection.CollectionUtil;
import com.baidu.aip.ocr.AipOcr;
import io.renren.entity.dto.BookPageSyncDto;
import io.renren.entity.dto.OcrResultBo;
import io.renren.es.dao.BookPageESDao;
import io.renren.utils.BaiduOcrUtils;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutTextMessage;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Slf4j
@Component
public class ImageHandler extends AbstractHandler {

    @Autowired
    private AipOcr aipOcr;

    @Autowired
    private BookPageESDao bookPageESDao;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService,
                                    WxSessionManager sessionManager) throws WxErrorException {
        log.info("进入图片处理器");
        if (StringUtils.isNotBlank(wxMessage.getPicUrl())) {
            OcrResultBo result4Sort = BaiduOcrUtils.getBaiduOcrResult4Sort(aipOcr, wxMessage.getPicUrl());
            BookPageSyncDto bookPageSyncDto = getValidateBookPage(result4Sort);
            log.info("查询结果[{}]", bookPageSyncDto);
            if (bookPageSyncDto != null) {
                String bookName = bookPageSyncDto.getBookName();
                Integer pageNo = bookPageSyncDto.getPageNo();
                String s = "《" + bookName + "》第" + pageNo + "页" +
                        "\n<a href = \"https://h5.yy.adp5.com.cn/hw3/stu/index" +
                        ".html#/page/contents?id=" + bookPageSyncDto.getId() + "\">点击连接开始检查答案</a>";
                WxMpXmlOutTextMessage m = WxMpXmlOutMessage.TEXT().content(s)
                        .fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser())
                        .build();
                return m;
            }
        }
        return null;
    }

    private List<BookPageSyncDto> getPaperInfoListByDao(String result) {
        SearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withPageable(PageRequest.of(0, 3))
                .withQuery(QueryBuilders.matchQuery("fullContent", result))
                .build();
        return bookPageESDao.search(searchQuery).toList();
    }

    /**
     * 获取校验的paperInfo
     *
     * @param ocrResultBo
     * @return
     */
    private BookPageSyncDto getValidateBookPage(OcrResultBo ocrResultBo) {
        List<BookPageSyncDto> bookPageList = getPaperInfoListByDao(ocrResultBo.getResult());
        log.info("查询结果数量[{}], 关键词数量:[{}]", bookPageList.size(), ocrResultBo.getKeyWordList().size());
        if (CollectionUtil.isEmpty(bookPageList)) {
            return null;
        }
        int keyWordCount = ocrResultBo.getKeyWordList().size();
        if (keyWordCount <= 0) {
            return null;
        }

        int threshold = 1;
        if (keyWordCount > 2) {
            threshold = (keyWordCount / 2) + 1;
        }

        for (BookPageSyncDto bookPageSyncDto : bookPageList) {
            String fullContent = bookPageSyncDto.getFullContent();
            long count = ocrResultBo.getKeyWordList().stream()
                    .filter(fullContent::contains)
                    .count();
            if (count >= threshold) {
                return bookPageSyncDto;
            }
        }

        return null;
    }
}
